<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Admin/classes/PhpFox_ComponentConfig.class.php, $Author:  $ */



/** Component for showing config blocks
 *
 * @version $Id: PhpFox_ComponentConfig.class.php 351 2008-02-18 20:15:54Z phpfoxsv $
 * @package module.admin
 */
class PhpFox_Mod_Admin_ComponentConfig extends BaseComponent
{
    function process()
    {
    	$oSrvAdmin = &$this->_oModule->getService('Admin');

        $oConfigItem = $this->_oModule->getItem('Config');
        /* @var $oConfigItem PhpFox_Mod_Admin_ItemConfig */
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oReq = &App::getRequest();
        $oTpl = &$this->_oModule->getTemplate();
       
        if ($iDid = $oReq->getInt('did')) 
        {
        	$this->oDatabase->_delete(App::getT('sys_sett'), "sett_id = '". $iDid ."'");
        	$this->oDatabase->_delete(App::getT('language_phrase'), "varname = 'Mod_Admin.param.". $oReq->get('dcode') ."' AND module = 'Mod_Admin'");
			$oLang =& App::getLanguage();
			$oLang->removeCachedFiles();
			Cache::rmFile('config.php');
        	App::gotoUrl('admin.config.options', array(), 'Removed!');
        }

       	$aCond = array
       	(
   	    	'block' => '= "'.$this->_aParams['mode'].'"',
   		);
   		
   		/*
   		$sLeftJoin = '';
   		$sGroupBy = '';
   		$sExtra = " AND block = '" . $this->_aParams['mode'] . "' ";
        if (($sBlock = $oReq->get('qblock')) && $sBlock == 'all')
        {
        	$sExtra = "";
        	$oTpl->assign('qblock', 'all');
        }
        
        if ($sQuery = $oReq->get('q')) 
        {       
        	$sQtype = $oReq->get('qtype');
        	// $sLeftJoin = " LEFT JOIN " . $this->oDatabase->getT('language_phrase') . " AS l ON (l.varname LIKE 'Mod_Admin.param.%' AND l.text LIKE '%" . $this->oDatabase->escape($sQuery) . "%')";
        	if ($sQtype == 'varname')
        	{
        		$sExtra .= ' AND code LIKE "%' . $this->oDatabase->escape($sQuery) . '%"';
        	}
        	else 
        	{
        		$sLeftJoin = " LEFT JOIN " . $this->oDatabase->getT('language_phrase') . " AS l ON (l.varname LIKE 'Mod_Admin.param.%' AND l.text LIKE '" . $this->oDatabase->escape($sQuery) . "')";
        		$sGroupBy = 'GROUP BY code';
        		$sExtra .= " AND block != 'hidden' ";
        	}
        	$oTpl->assign('q', $sQuery);
        }
        */
        
        $sLogicUrl = App::getPageName();
        list($aItems, $iCnt) = $oConfigItem->getList($aCond, 0, 0, 'pos');
		/*
        $iCnt = $this->oDatabase->getField("
        	SELECT 
        		COUNT(*)
        	FROM " . $this->oDatabase->getT('sys_sett') . "
        	" . $sLeftJoin . "
        	WHERE 1
        	" . $sExtra . "
        	" . $sGroupBy ."	
        	ORDER BY pos ASC
        ");		
        
        $aItems = $this->oDatabase->getRows("
        	SELECT 
        		*
        	FROM " . $this->oDatabase->getT('sys_sett') . "
        	" . $sLeftJoin . "
        	WHERE 1
        	" . $sExtra . "
        	" . $sGroupBy ."
        	ORDER BY pos ASC
        ");
        */

        $aValidation = App::getParam('Mod_Admin.config_validation');
        $aValForUse = array();
        foreach ($aItems as $aItem)
        {
            if (array_key_exists($aItem['code'], $aValidation))
            {
                $aValForUse[$aItem['code']] = $aValidation[$aItem['code']];
            }
        }
        $oValidator = null;
        if (count($aValForUse))
        {
            $aFields = array();
            foreach ($aValForUse as $sKey => $aField)
            {
                $aField['title'] = App::format($aField['title']);
                $aFields['val['.$sKey.']'] = $aField;
            }
            $oValidator = &App::newObject('Validator', $aFields);
            /* @var $oValidator Validator */

            $oTpl->assignSrc(array(
                'sJsValMess' => $oValidator->makeJsMess(),
                'sJsVal'     => $oValidator->makeJS(),
            ));
        }

        $sBlockName = 'config_'.$this->_aParams['mode'];
        if (($oReq->getAction() == 'save') && ($sBlockName == $oReq->get('block')))
        {
            if ($oValidator != null)
            {
                if (!$oValidator->isValid($oReq->getAll()))
                {
                    $this->addErrors($oValidator->getErrors());
                }
            }
            $aValues = $oReq->getArray('val');

            if ('config_pay' == $sBlockName)
            {
                if (App::getSetting('payment_paypal_email') != $aValues['payment_paypal_email'])
                {
                    $iPending = $oConfigItem->oDb->countRows('SELECT * FROM ' . App::getT('sale') . ' WHERE status = "pending"');
                    if ($iPending > 0)
                    {
                        $this->addErrors(App::format('Mod_Admin.errors.cant.change.pp.mail'));
                    }
                }
            }

            if ('config_video' == $sBlockName)
            {
            	if ( (isset($aValues['vid_use_ffmpeg']) && $aValues['vid_use_ffmpeg'] == '1'))
            	{
            		$oSrvVideo = &App::getModuleService('Video', 'Video');
            		list($bFfmpegInstalled, $sErrorValue) = $oSrvVideo->check_requirements();
            		if ( !$bFfmpegInstalled )
            		{
						$this->addErrors($sErrorValue);
					}
				}
            }

            if (!count($this->getErrors()))
            {
                $aValues = $oReq->getArray('val');
                $aPos = $oReq->getArray('pos');
                
                foreach ($aPos as $sKey => $sValue) 
                {             
                	$this->oDatabase->update($this->oDatabase->getT('sys_sett'), array('pos' => $sValue), "code = '" . $sKey . "'");
                }                
        
                foreach ($aItems as $iKey => $aItem)
                {
                    $oConfigItem->load($aItem['sett_id']);
                    $oConfigItem->aData['val'] = $aValues[$aItem['code']];                    
                    $oConfigItem->update(array('val'));
                }
                
            	$aUrlParams = array();
            	if ($sBlockName == 'config_music' && isset($aValues['bSongSecurity']) && $aValues['bSongSecurity'] == '1' && !App::getParam('bSongSecurity'))
            	{
            		$aUrlParams['secure'] = 'music';
            	}   
            	elseif ($sBlockName == 'config_video' && isset($aValues['bVideoSecurity']) && $aValues['bVideoSecurity'] == '1' && !App::getParam('bVideoSecurity'))
            	{
            		$aUrlParams['secure'] = 'video';
            	}
            	elseif ($sBlockName == 'config_image' && isset($aValues['bImageSecurity']) && $aValues['bImageSecurity'] == '1' && !App::getParam('bImageSecurity'))
            	{
            		$aUrlParams['secure'] = 'image';
            	}                
                
                App::deleteSetting();
                $oSrvMenu = &App::getModuleService('Menu', 'Menu');
                $oSrvMenu->_cacheMenu(true);      	

                if ( $sNewRedirect = $oReq->get('edit') )
            	{
            		$aUrlParams['edit'] = $sNewRedirect;
            		App::gotoUrl('admin.config.core', $aUrlParams, App::format('Mod_Admin.param_saved'), false, $sBlockName);
            	}
            		
                App::gotoUrl($sLogicUrl, $aUrlParams, App::format('Mod_Admin.param_saved'), false, $sBlockName);
            }

            App::gotoUrl($sLogicUrl, array(), $this->getErrors(), true, $sBlockName);
        }

        foreach ($aItems as $iKey => $aItem)
        {
            $aItems[$iKey]['title']       = App::format('Mod_Admin.param.'.$aItem['code']);
            $aItems[$iKey]['description'] = App::format('Mod_Admin.paramd.'.$aItem['code']);
            if ($aItem['code'] == 'new_friend')
            {
                $aArr = array();
                $aArr[''] = '------------';
                list($aAdmins, $iCnt) = $oAccountService->getStuffList();
                foreach ($aAdmins as $aAdmin)
                {
                    $aArr[$aAdmin['user']] = $aAdmin['user'];
                }
                $aItems[$iKey]['select'] = $aArr;
            }
            elseif ($aItem['code'] == 'singup_pic_upload')
            {
                $aArr = array();
                $aArr['1'] = App::format('Mod_Admin.yes');
                $aArr['2'] = App::format('Mod_Admin.optional');
                $aArr[''] = App::format('Mod_Admin.no');
                $aItems[$iKey]['select'] = $aArr;
            }
            elseif($aItems[$iKey]['code'] == 'payment_paypal_currency')
            {
                $aArr = array('USD'=>'USD', 'GBP'=>'GBP', 'EUR'=>'EUR', 'CAD'=>'CAD', 'JPY'=>'JPY');
                $aItems[$iKey]['select'] = $aArr;
            }
            elseif($aItems[$iKey]['code'] == 'mail_type')
            {
                $aArr = array('mail' => 'mail', 'smtp' => 'smtp');
                $aItems[$iKey]['select'] = $aArr;
            }
            elseif($aItems[$iKey]['code'] == 'image.im.use')
            {
                $aArr = array('mail' => 'mail', 'smtp' => 'smtp');
                $aItems[$iKey]['select'] = array('' => 'GD', '1' => 'ImageMagick');
            }            
            elseif($aItems[$iKey]['code'] == 'vid_import')
            {
            	$aVideoSites = App::getParam('Mod_Video.stream_sources');
            	$aSupportedSites = "";
            	$iSites = 0;
            	foreach($aVideoSites as $aSite)
            	{
            		if ( $aSite['import'] )
            		{
            			$iSites++;
            			if ( $iSites != 1 )
            			{
            				$aSupportedSites .= ", ";
            			}
            			$aSupportedSites .= App::format('Mod_Admin.support_sites', $aSite['name']);
            		}
            	}
                $aItems[$iKey]['extra_info'] = $aSupportedSites;
            }            
        	elseif($aItems[$iKey]['code'] == 'public.top.friends')
        	{
                $aItems[$iKey]['select'] = array(6 => 6, 12 => 12, 18 => 18, 24 => 24, 30 => 30, 36 => 36, 42 => 42);
        	}      
        	elseif($aItems[$iKey]['code'] == 'bVideoSecurity' && !App::getParam('rewrite_engine'))
        	{
        		$aItems[$iKey]['bIsHidden'] = true;
        	}
        	elseif($aItems[$iKey]['code'] == 'bSongSecurity' && !App::getParam('rewrite_engine'))
        	{
        		$aItems[$iKey]['bIsHidden'] = true;
        	}
        	elseif($aItems[$iKey]['code'] == 'bImageSecurity' && !App::getParam('rewrite_engine'))
        	{
        		$aItems[$iKey]['bIsHidden'] = true;
        	}    
        }

		if ( 'ffmpeg' == $this->_aParams['mode'] )
        {
			$oSrvVideo = &App::getModuleService('Video', 'Video');
			list($bFfmpegInstalled, $sErrorValue) = $oSrvVideo->check_requirements();
			if ( !$bFfmpegInstalled )
			{
				$sHideBlock = $sErrorValue;
			}
		}

		if ( $this->_aParams['mode'] == 'subscription' )
		{
			if ( !extension_loaded('curl') )
			{
          		$sHideBlock = App::format('Mod_Admin.no_curl');
        	}
        }
        
        $sSecure = '';
        if ($sBlockName == 'config_music' || $sBlockName == 'config_video' || $sBlockName == 'config_image')
        {
	        if (($sSecureModule = $oReq->get('secure')) && App::getParam('rewrite_engine'))
	        {
	        	$sSubFolder = str_replace(App::getParam('domain'), '', App::getParam('host'));        	
	        	$sSecure = App::getParam('Mod_Admin.protect_rewrite', $sSecureModule);
	        	$sSecure = str_replace('<SUB_FOLDER>', $sSubFolder, $sSecure);
	        }
        }
	        
        $oTpl->assignSrc('aItems', $aItems);
        $oTpl->assign(array(
            'sTitle'     => App::format('Mod_Admin.config.'.$this->_aParams['mode']),
            'sSubmitUrl' => App::makeUrl($sLogicUrl, array('block' => $sBlockName, 'edit' => $this->getParam('direct'))),
            'sBlockName' => $sBlockName,
            'sHideBlock' => (isset($sHideBlock) ? $sHideBlock : ''),
            'aOptions' => $oSrvAdmin->getOptions(),
            'sSecure' => $sSecure
        ));
        return $oTpl->fetch('Config.html');
    }
}
?>